﻿namespace DCHealthCheck {

    #region Usings
    using DCHealthCheck.Common;
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Text;
    using System.Threading; 
    #endregion

    class Program {

        private static log4net.ILog Log { get; set; }
        private static Mutex mutex;

        static void Main(string[] args) {
            // single-instance validation using mutex
            bool firstApplicationInstance;
            string mutexName = "DCHealthCheck.exe{d70d07cf-2d31-4695-8d0f-d69f08d32a2a}";
            Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            using (mutex = new Mutex(false, mutexName, out firstApplicationInstance)) {
                if (!firstApplicationInstance) {
                    Log.Warn("Another instance is already running, application will now exit.");
                    return;
                }

                Trace.Listeners.Add(new Log4netTraceListener(Log));
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                HealthCheckRunner.DoWork();
            }
        }

        /// <summary>
        /// Unhandled Exception Logger
        /// </summary>
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
            Exception exception = e.ExceptionObject as Exception;
            Log.ErrorFormat("Unhandled Exception: {0}", exception.VerboseExceptionString());
        }
    }
}
